package com.topisv.tms.service.stock.reverse;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.stock.CusStock;
import com.topisv.tms.entity.stock.check.CheckPlan;
import com.topisv.tms.entity.stock.instorage.InstorageInfo;
import com.topisv.tms.entity.stock.instorage.OutstorageInfo;
import com.topisv.tms.entity.stock.reverse.ReverseBill;
import com.topisv.tms.entity.stock.reverse.ReverseBillItem;
import com.topisv.tms.repository.AreaGroupDao;
import com.topisv.tms.repository.CustomersDao;
import com.topisv.tms.repository.UserDao;
import com.topisv.tms.repository.stock.CusStockDao;
import com.topisv.tms.repository.stock.check.CheckPlanDao;
import com.topisv.tms.repository.stock.instorage.InstorageInfoDao;
import com.topisv.tms.repository.stock.instorage.OutstorageInfoDao;
import com.topisv.tms.repository.stock.reverse.ReverseBillDao;
import com.topisv.tms.repository.stock.reverse.ReverseBillItemDao;
import com.topisv.tms.rest.qimen.qmsend.QmRequestSender;
import com.topisv.tms.rest.qimen.qmservice.StockReportService;
import com.topisv.tms.service.md.MDCheckInOrOutService;
import com.topisv.tms.service.stock.outstorage.OutstorageBillService;
/**
 * 冲正单明细_service
 * @author ch
 *
 */
@Component
@Transactional(readOnly = true)
public class ReverseBillItemService {
	private static final Logger logger = LoggerFactory.getLogger(ReverseBillItemService.class);
	@Autowired
	private ReverseBillItemDao reverseBillItemDao;
	@Autowired
	private CustomersDao customersDao;
	@Autowired
	private AreaGroupDao areaGroupDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private CusStockDao cusStockDao;
	@Autowired
	private ReverseBillDao reverseBillDao;
	@Autowired
	private CheckPlanDao checkPlanDao;
	@Autowired
	private MDCheckInOrOutService mdCheckInOrOutService;
	@Autowired
	private OutstorageBillService outstorageBillService;
	@Autowired
	private InstorageInfoDao instorageInfoDao;
	@Autowired
	private OutstorageInfoDao outstorageInfoDao;
	@Resource(type=StockReportService.class)
	QmRequestSender<CheckPlan> stockReportService;
	/**
	 * 查询
	 * @param billCode 冲正单编码
	 * @return
	 */
	public List<ReverseBillItem> loadByBillCode(String billCode) {
		List<ReverseBillItem> list= this.reverseBillItemDao.loadByBillCode(billCode);
		for (ReverseBillItem item : list) {
			this.setDetail(item);
		}
		return list;
	}

	/**
	 * 查询
	 * @param billItemId 
	 * @return
	 */
	public ReverseBillItem loadById(Long billItemId) {
		ReverseBillItem item= this.reverseBillItemDao.findOne(billItemId);
		this.setDetail(item);
		return item;
	}
	
	
	
	/**
	 * 设置属性
	 * @param bill
	 */
	private void setDetail(ReverseBillItem item) {
		//customer
		String customerCode=item.getCustomerCode();
		Customers customer=this.customersDao.findByCustomerCode(customerCode);
		item.setCustomer(customer);
		
		//warehouse
		String warehouseCode=item.getWarehouseCode();
		AreaGroup warehouse=this.areaGroupDao.findByGroupCode(warehouseCode);
		item.setWarehouse(warehouse);
		
		//duter
		User user=this.userDao.findByJobuuid(item.getDutyUuid());
		item.setDuter(user);
		
		//reverser
		User reverser=this.userDao.findByJobuuid(item.getReverserUuid());
		item.setReverser(reverser);
		
	}

	/**
	 * 冲正
	 * @param billItemId 冲正明细Id
	 * @param dutyUuid 责任人
	 * @param dutyReason 责任说明
	 * @param reverserUuid 冲正人
	 * @throws Exception 
	 */
	@Transactional(readOnly=false,rollbackFor=Exception.class)
	public String reverse(Long billItemId, String dutyUuid, String dutyReason,String stockCode,String boxCode,String reverserUuid) throws Exception {
		try {
			
			ReverseBillItem item=this.reverseBillItemDao.findOne(billItemId);
			
			//验证
			String status=item.getStatus();
			if(!"undo".equals(status)){
				return "done"; //已经冲正了
			}
			
			//修改状态
			Date now=new Date();
			item.setStatus("done");
			item.setDutyReason(dutyReason);
			item.setDutyUuid(dutyUuid);
			item.setReverserUuid(reverserUuid);
			item.setReverseTime(now);
			item.setStockCode(stockCode);
			item.setBoxCode(boxCode);
			this.reverseBillItemDao.save(item);
			
			//修改库存
			CusStock stock=this.cusStockDao.loadStock(item.getCustomerCode(),item.getWarehouseCode(),  item.getStockCode(), item.getBoxCode(), item.getSku());
			if(stock==null){
//				库存信息不存在
				stock= new CusStock();
				stock=new CusStock();
		   		stock.setBoxCode(boxCode);
		   		stock.setSku(item.getSku());
		   		stock.setCustomerCode(item.getCustomerCode());
		   		Customers customer=this.customersDao.findByCustomerCode(item.getCustomerCode());
		   		stock.setCustomer(customer);
		   		AreaGroup warehouse=this.areaGroupDao.findByGroupCode(item.getWarehouseCode());
		   		stock.setWarehouse(warehouse);
		   		stock.setWarehouseCode(item.getWarehouseCode());
		   		stock.setStockCode(stockCode);
		   		stock.setSalesNum(item.getSalesNumFix());
		   		stock.setUnusedNum(item.getUnusedNumFix());
		   		stock.setOrderNum(item.getOrderNumFix());
		   		stock.setLockedNum(0);
		   		stock.setTransportNum(0);
		   		stock.setAirNum(0);
		   		
		   		User worker=this.userDao.findByJobuuid(reverserUuid);
		   		
			   	stock.setLastmodifyTime(now);
			   	stock.setLastopetator(worker);
			   	stock.setStockType("1");
			   	this.cusStockDao.save(stock);
			}else {
				stock.setSalesNum(stock.getSalesNum()+item.getSalesNumFix());
				stock.setUnusedNum(stock.getUnusedNum()+item.getUnusedNumFix());
				stock.setOrderNum(stock.getOrderNum()+item.getOrderNumFix());
				this.cusStockDao.save(stock);
			}
			
			
			//写入库存出入信息表
			if( (item.getSalesNumFix() != 0 && item.getSalesNumFix() > 0) 
					||  (item.getUnusedNumFix() != 0 && item.getUnusedNumFix() > 0) 
					||  (item.getOrderNumFix() != 0 && item.getOrderNumFix() > 0)) {
				InstorageInfo ii = new InstorageInfo();
				ii.setCustomerCode(item.getCustomerCode());
				ii.setWarehouseCode(item.getWarehouseCode());
				ii.setBillCode("");
				ii.setUptaskCode(null);
				ii.setSku(item.getSku());
				if(item.getSalesNumFix() != 0 ){
					ii.setNum(item.getSalesNumFix());
				}else if(item.getOrderNumFix() != 0 ){
					ii.setNum(item.getOrderNumFix());
				}else {
					ii.setNum(item.getUnusedNumFix());
				}
				if(ii.getNum()<0){
					ii.setNum(ii.getNum()*-1);
				}
				ii.setOpeTime(new Date());
				ii.setBillType("check");
				ii.setAboutCode(item.getBillCode());
				//插入库存出入信息表
				if(item.getSalesNumFix() != 0 || item.getOrderNumFix() != 0){
					ii.setErrorFlag("noterror");
				}else {
					ii.setErrorFlag("error");
				}
				instorageInfoDao.save(ii);
			} else if( (item.getSalesNumFix() != 0 && item.getSalesNumFix() < 0) 
					||  (item.getUnusedNumFix() != 0 && item.getUnusedNumFix() < 0) 
					||  (item.getOrderNumFix() != 0 && item.getOrderNumFix() < 0) ) {
				OutstorageInfo oi = new OutstorageInfo();
				oi.setCustomerCode(item.getCustomerCode());
				oi.setWarehouseCode(item.getWarehouseCode());
				oi.setBatchCode(null);
				oi.setTaskCode(null);
				oi.setSku(item.getSku());
				if(item.getSalesNumFix() != 0 ){
					oi.setNum(item.getSalesNumFix());
				}else if(item.getOrderNumFix() != 0 ){
					oi.setNum(item.getOrderNumFix());
				}else {
					oi.setNum(item.getUnusedNumFix());
				}
				if(oi.getNum()<0){
					oi.setNum(oi.getNum()*-1);
				}
//				oi.setNum(item.getUnusedNumFix());
				oi.setOpeTime(new Date());
				oi.setBillType("check");
				oi.setAboutCode(item.getBillCode());
				outstorageInfoDao.save(oi);
			}
			
			
			//查看同一冲正单其它明细是否都已经冲正
			List<ReverseBillItem> itemList=this.reverseBillItemDao.loadUnreverseItemByBillCode(item.getBillCode());
			ReverseBill bill=this.reverseBillDao.loadByCode(item.getBillCode());
			if(itemList.size()==0){ //冲正完毕
				bill.setStatus("finish");
				try{
				ReverseBill reverseBill = reverseBillDao.loadByCode(item.getBillCode());
//				if(reverseBill.getAboutCode()!=null&&!(reverseBill.getAboutCode()).equals("")){
					logger.info("--调用奇门接口PlanCode:"+reverseBill.getAboutCode() );
					CheckPlan params = checkPlanDao.loadByPlanCode(reverseBill.getAboutCode()); 
					stockReportService.send(params,params.getCustomerCode());
//				}
				}catch(Exception e){
					logger.error("--奇门调用盘点 error");
				}
			}else{
				bill.setStatus("doing");
			}
			this.reverseBillDao.save(bill);
			
			if("finish".equals(bill.getStatus())){
				//回传美的盘点出入库
				mdCheckInOrOutService.sendMDCheckInOrOut(item.getBillCode());
//				outstorageBillService.sendEdb(item.getBillCode());//回调E店宝
			}
			
			return "success";
			
		} catch (Exception e) {
			throw e;
		}
	}
	
}
